package cn.highedu.controller;

import cn.highedu.entity.Order;

import io.micrometer.core.annotation.Timed;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class OrderController {
    // 来自 https://micrometer.io/docs/concepts
    // 用于记录订单提交的时间
    private Timer timer;

    public OrderController(MeterRegistry registry) {
        // 注册一个 Timer, 用于记录订单提交的时间
        this.timer = registry.timer("orders.submit");
    }

    @PostMapping("/orders")
    public Order placeOrder(@RequestBody Order order) {
        // 用于记录订单提交的时间, 关注点混合
        return timer.record(() -> {
            // 记录订单提交的时间
            return updateOrder(order);
        });
    }

    private Order updateOrder(Order order) {
        // ...
        System.out.println(order);
        return new Order(1L, "order");
    }

    @GetMapping("/orders")
    @Timed("orders.summary") // 用于记录订单汇总的时间
    public List<Order> orderSummary() {
        List<Order> orders = new ArrayList<>();
        orders.add(new Order(1L, "order1"));
        orders.add(new Order(2L, "order2"));
        return orders;
    }

}
